//
//  AIGirlMessageBottomView.swift
//  AIGirl
//
//  Created by Rae on 2024/1/2.
//

import UIKit

class AIGirlMessageBottomView: UIView, UITextViewDelegate {

    private var shadowView = UIView()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private var dataArray: [AIGirlUserInterestItemModel] = [
//        AIGirlMessageCateModel(title: "236",imgStr: "AIGirl_Home_purpleDiamond"),
//        AIGirlMessageCateModel(title: "Gift",imgStr: "AIGirl_Message_gift"),
//        AIGirlMessageCateModel(title: "Photo",imgStr: "AIGirl_Message_pic")
        AIGirlUserInterestItemModel(name: "236", img: "AIGirl_Home_purpleDiamond"),
        AIGirlUserInterestItemModel(name: "Gift", img: "AIGirl_Message_gift"),
        AIGirlUserInterestItemModel(name: "Photo", img: "AIGirl_Message_pic")
    ]
    lazy var descView: AIGirlChatTextView = {
        let view = AIGirlChatTextView()
        view.backgroundColor = "#FBFBFB".toColor.alpha(0.2)
        view.textContainerInset = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 55)
        view.tintColor = .white
        view.textColor = .white
        view.placeHolderColor = "#A7A7A7".toColor
        view.placeHolder = "Replying to girl"
        view.placeholderFont = 16.font_medium
        view.returnKeyType = .done
        view.font = 16.font_medium
        view.layer.cornerRadius = 25
        view.layer.masksToBounds = true
        return view
    }()
     lazy var sendBtn = c_make_ex(UIButton.self)
        .image("AIGirl_Message_send").end()
    var interestData: [AIGirlUserInterestItemModel]? {
        didSet{
            if let array = interestData, array.count > 0 {
//                for md in array {
//                    dataArray.append(md)
//                }
//                var result = [AIGirlUserInterestItemModel]()
                for item in array {
                    let elements = dataArray.map { $0.id}
                    if !elements.contains(item.id) {
                        dataArray.append(item)
                    }
                }
                collectionView.reloadData()
            }
        }
    }
    
    var sendClosure: ((_ msg: String) -> Void)?
    var diamondClosure: (() -> Void)?
    var giftClosure: (() -> Void)?
    var phototClosure: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            shadowView
            collectionView
            descView
            sendBtn
        }
        
        shadowView.fillContainer()
        collectionView.leading(0).trailing(0).top(8).height(30)
        descView.leading(15).trailing(15).height(50)
        descView.Top == collectionView.Bottom + 13
        sendBtn.trailing(30).size(24)
        sendBtn.CenterY == descView.CenterY
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15.0, bottom: 0, right: 0)
        layout.scrollDirection = .horizontal
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlMessageCateItem.self, forCellWithReuseIdentifier: AIGirlMessageCateItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        descView.delegate = self
        sendBtn.addTarget(self, action: #selector(clickSentButton), for: .touchUpInside)
        NotificationCenter.default.addObserver(forName: .userBalanceChanged, object: nil, queue: nil) { noti in
            self.collectionView.reloadData()
        }
    }
    
    @objc private func clickSentButton(){
        
        if let text = descView.text, text.count > 0{
            sendClosure?(text)
            descView.text = ""
        }else{
            "Chat content cannot be empty!".toast_error
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        shadowView.fj.gradientColors(.topToBottom(["#111012".toColor.alpha(0),"#151417".toColor]))
    }

    // 实现 UITextViewDelegate 协议中的方法
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        // 获取当前文本的字符数
        let currentText = textView.text as NSString
        let updatedText = currentText.replacingCharacters(in: range, with: text)

        // 设置最大字符数
        let maxLength = 300
        
        // 判断是否超过最大字符数
        if updatedText.count <= maxLength {
            return true // 允许输入
        } else {
            // 如果超过最大字符数，截断文本
            let limitedText = updatedText.prefix(maxLength)
            textView.text = String(limitedText)
            return false // 阻止继续输入
        }
    }
}

extension AIGirlMessageBottomView: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlMessageCateItem.description(), for: indexPath) as? AIGirlMessageCateItem else { return UICollectionViewCell() }
        var model = dataArray[indexPath.row]
        if indexPath.row == 0 {
            let coin = GlobalTool.userModel?.money ?? 0
            model.name = String(coin)
        }
        item.model = model
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if indexPath.row == 0 {
            diamondClosure?()
        }else if indexPath.row == 1 {
            giftClosure?()
        }else if indexPath.row == 2 {
            phototClosure?()
        }else {
            let model = dataArray[indexPath.row]
            var text = "没有配聊天话术"
            if model.recommendationSpeech.count > 0 {
                text = model.recommendationSpeech
            }
            sendClosure?(text)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let model = dataArray[indexPath.row]
//        var w = model.name.caculateWidth(CGSize(width: 75, height: 30), 20.font_regular!)
        var w = model.name.size(withAttributes: [NSAttributedString.Key.font: 17.font_regular!]).width
        if model.img.count > 0 {
            w = w + 55.0
        }else{
            w = w + 33.0
        }
        return CGSize(width: w, height: 30)
    }
}


class AIGirlMessageCateItem: UICollectionViewCell {
    
        private var iconImg = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
        private var contentLab = c_make_ex(UILabel.self)
        .color(.white).font(17.font_regular).end()
    
    
    var model: AIGirlUserInterestItemModel? {
        didSet{
            guard let md = model else { return }
            if md.img.count > 0 {
                iconImg.isHidden = false
                iconImg.image = md.img.toImage
                contentLab.leadingConstraint?.constant = 40
            }else{
                iconImg.isHidden = true
                contentLab.leadingConstraint?.constant = 13
            }
            contentLab.text = md.name
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = .clear
        layer.cornerRadius = 15
        layer.borderColor = UIColor.white.alpha(0.2).cgColor
        layer.borderWidth = 1
        layer.masksToBounds = true
        
        contentView.subviews {
            iconImg
            contentLab
        }
        iconImg.leading(10).size(22).centerVertically()
        contentLab.trailing(10).leading(40).centerVertically()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
